package com.red.star.wechat.data.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.red.star.wechat.data.core.constant.Constant;
import com.red.star.wechat.data.entity.*;
import com.red.star.wechat.data.entity.bo.EmployeeBo;
import com.red.star.wechat.data.mappers.*;
import com.red.star.wechat.data.utils.CheckUtil;
import com.red.star.wechat.data.utils.DateNewUtil;
import com.red.star.wechat.data.utils.TicketUtil;
import com.red.star.wechat.data.utils.WeiXinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
 * @ProjectName: macalline-work-server
 * @Package: com.red.star.macalline.data.service
 * @Description:
 * @Author: AMGuo
 * @CreateDate: 2018/7/24 上午11:49
 * @Version: 1.0
 */
@Service
public class UserApiService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserApiService.class);

    @Resource
    private MerchantMapper merchantMapper;

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private VipMapper vipMapper;

    @Resource
    private FansMapper fansMapper;

    @Resource
    private MallMapper mallMapper;

    /**
     * 微信同步导购数据
     *
     * @param jsonObject
     * @param fans
     * @return
     */
    public Vip syncEmployee(JSONObject jsonObject, Fans fans) {
        Vip responseVip = null;
        if (!CheckUtil.isEmpty(jsonObject)) {
            LOGGER.info("获取导购员|管理员信息：" + jsonObject.toJSONString());
            String omsCode = jsonObject.getString("unit_code");
            String vipId = jsonObject.getString("vip_id");
            String belongShop = jsonObject.getString("belong_shop");
            String mobile = jsonObject.getString("vip_cell");
            String vipOpenId = jsonObject.getString("crm_openid");
            String vipName = jsonObject.getString("vip_name");
            //员工类型    1员工 2营业员
            Integer unitEmployeeType = jsonObject.getInteger("unit_employee_type");
            JSONObject fansObject = jsonObject.getJSONObject("fans");
            fansObject = CheckUtil.isEmpty(fansObject) ? new JSONObject() : fansObject;
            String vipString = fansObject.getString("Vip");
            Date currentDateTime = DateNewUtil.getCurrentDateTime();
            Mall mall = null;
            if (!CheckUtil.isEmpty(omsCode)) {
                mall = new Mall();
                mall.setOmsCode(omsCode);
                mall = mallMapper.selectOne(mall);
            }
            if (!CheckUtil.isEmpty(mall)) {
                if (Constant.INTEGER_2.equals(unitEmployeeType)) {
                    unitEmployeeType = Constant.INTEGER_0;
                }
                Merchant merchant = merchantMapper.findOnlyByMallAShop(mall.getMallCode(), belongShop);
                if (Constant.INTEGER_0.equals(unitEmployeeType) && null == merchant) {
                    return responseVip;
                }
                merchant = CheckUtil.isEmpty(merchant) ? new Merchant() : merchant;
                //新增vip
                Vip vip = new Vip(mobile, vipOpenId, vipId, vipName, currentDateTime, mall.getMallCode(), mall.getOmsCode());
                vip.setCreateTime(currentDateTime);
                vip.setUpdateTime(currentDateTime);
                vip.setSyncVip(vipString);
                responseVip = vip;
                //新增employee
                Employee employee = new Employee(vipName, mobile, mall.getMallCode(), !Constant.INTEGER_0.equals(unitEmployeeType) ? null : merchant.getId(), vipOpenId, vipId, 0,
                        currentDateTime, unitEmployeeType, fans.getId());
                employee.setCreateTime(currentDateTime);
                employee.setUpdateTime(currentDateTime);
                //防止重复提交
                int j = 0;
                int n = 0;
                synchronized (this) {
                    //是否登录
                    Boolean logonFlag = CheckUtil.isEmpty(fans.getVipOpenId()) ? false : true;
                    if (logonFlag) {
                        //已登录——不更新vip，只更新employee(vipOpenId还是之前的)
                        Vip vipOld = vipMapper.getVipByVipOpenId(fans.getVipOpenId());
                        vip.setVipOpenId(vipOld.getVipOpenId());
                        vip.setMobile(vipOld.getMobile());
                        vip.setSyncVip(vipString);
                        vip.setId(vipOld.getId());
                        n = vipMapper.updateByPrimaryKeySelective(vip);
                        employee.setVipOpenId(vipOld.getVipOpenId());
                        employee.setMobile(vipOld.getMobile());
                    } else {
                        //未登录——更新vip，employee
                        //更新fans
                        fans.setVipOpenId(vipOpenId);
                        //保存vip信息
                        Integer m = vipMapper.findSelective(vip);
                        if (CheckUtil.isEmpty(m)) {
                            n = vipMapper.insertSelective(vip);
                        } else {
                            vip.setId(m);
                            n = vipMapper.updateByPrimaryKeySelective(vip);
                        }
                    }
                    //保存导购信息
                    Integer i = employeeMapper.findEffectiveByCondition(employee);
                    if (CheckUtil.isEmpty(i)) {
                        j = employeeMapper.insertSelective(employee);
                    } else {
                        // 存在，先解绑再绑定
                        int k = employeeMapper.updateStatusById(i, Constant.INTEGER_1);
                        if (k == 1) {
                            j = employeeMapper.insertSelective(employee);
                        }
                    }
                }
                if (j != 0) {
                    if (Constant.INTEGER_0.equals(unitEmployeeType) || Constant.INTEGER_1.equals(unitEmployeeType)) {
                        //b端
                        fans.setType(1);
                    } else {
                        fans.setType(0);
                    }
                    //同步数据到仟传
                    syncQianChuan(fans, vip, mall, employee);
                    //同步数据到微信后台
                    syncWXGZBind(employee);
                }
                fansMapper.updateByPrimaryKeySelective(fans);
                LOGGER.info("register更新vip-code:{}msg:{} || employee-code:{}msg:{}", n, vip.toString(), j, employee.toString());
            }
        }
        return responseVip;
    }

    /**
     * 绑定导购、管理员 同步数据到仟传
     *
     * @param oldFans
     * @param vip
     * @param mall
     * @param employee
     */
    @Async
    public void syncQianChuan(Fans oldFans, Vip vip, Mall mall, Employee employee) {
        if (!CheckUtil.isEmpty(oldFans) && !CheckUtil.isEmpty(oldFans.getUnionId()) && !CheckUtil.isEmpty(employee)) {
            try {
                JSONObject jsonObject = TicketUtil.getWxOpenidByUnionid(oldFans.getUnionId());
                if (!CheckUtil.isEmpty(jsonObject) && !CheckUtil.isEmpty(jsonObject.getString("openid"))) {
                    LOGGER.info("绑定管理员|获取公众号openId:" + jsonObject.toJSONString());
                    // 仟传数据同步
                    String openid = jsonObject.getString("openid");
                    String name = vip.getName();
                    String mobile = vip.getMobile();
                    String omsCode = mall.getOmsCode();
                    Integer type = employee.getType();
                    if (Constant.INTEGER_0.equals(type)) {
                        //导购
                        type = Constant.INTEGER_2;
                    }
                    String response = WeiXinUtil.addWhiteList(openid, name, omsCode, mobile, type);
                    LOGGER.info("仟传|绑定管理员:" + response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 同步导购、管理员到微信后台
     *
     * @param employee
     */
    @Async
    public void syncWXGZBind(Employee employee) {
        if (!CheckUtil.isEmpty(employee) && !CheckUtil.isEmpty(employee.getId())) {
            EmployeeBo employeeBo = employeeMapper.findEmployeeById(employee.getId());
            if (!CheckUtil.isEmpty(employeeBo)) {
                try {
                    JSONObject jsonObject = TicketUtil.bindEmployee(employeeBo);
                    LOGGER.info(Constant.MSG_INFO_SYNCWXGZBIND + jsonObject);
                } catch (IOException e) {
                    LOGGER.error(Constant.MSG_ERROR_SYNCWXGZBIND + JSON.toJSONString(e));
                }
            }
        }
    }

    /**
     * 微信同步vip数据
     *
     * @param vipString
     * @return
     */
    public Vip syncVip(String vipString) {
        Vip vip = null;
        if (!CheckUtil.isEmpty(vipString)) {
            JSONObject jsonObject = JSONObject.parseObject(vipString);
            if (!CheckUtil.isEmpty(jsonObject)) {
                String openid = jsonObject.getString("Openid");
                JSONObject vipObject = jsonObject.getJSONObject("Vip");
                if (!CheckUtil.isEmpty(openid) && !CheckUtil.isEmpty(vipObject)) {
                    //只有新用户才会同步
                    Fans fans = fansMapper.findFansByOpenId(openid);
                    if (!CheckUtil.isEmpty(fans) && CheckUtil.isEmpty(fans.getVipOpenId())) {
                        String vipId = vipObject.getString("vip_id");
                        String mobile = vipObject.getString("vip_cell");
                        String vipOpenId = vipObject.getString("crm_openid");
                        String vipName = vipObject.getString("vip_name");
                        String registUnitCode = vipObject.getString("regist_unit_code");
                        Date currentDateTime = DateNewUtil.getCurrentDateTime();
                        Mall mall = new Mall();
                        if (!CheckUtil.isEmpty(registUnitCode)) {
                            mall.setOmsCode(registUnitCode);
                            mall = mallMapper.selectOne(mall);
                        }
                        //新增vip
                        vip = new Vip(mobile, vipOpenId, vipId, vipName, currentDateTime, mall.getMallCode(), mall.getOmsCode());
                        vip.setCreateTime(currentDateTime);
                        vip.setUpdateTime(currentDateTime);
                        vip.setSyncVip(JSON.toJSONString(vipObject));
                        int i = 0;
                        Integer oldVipId = vipMapper.findSelective(vip);
                        if (!CheckUtil.isEmpty(oldVipId)) {
                            vip.setId(oldVipId);
                            i = vipMapper.updateByPrimaryKeySelective(vip);
                        } else {
                            i = vipMapper.insertSelective(vip);
                        }
                        int j = 0;
                        if (i == 1) {
                            fans.setVipOpenId(vipOpenId);
                            j = fansMapper.updateByPrimaryKeySelective(fans);
                        }
                        LOGGER.info("微信同步vip数据：vip新增成功条数：{}，vip：{}；fans更新成功条数：{}，fans：{}", i, JSON.toJSONString(vip), j, JSON.toJSONString(fans));
                    } else {
                        LOGGER.warn("微信同步vip数据：用户openid:{}已是vip！", openid);
                    }
                } else {
                    LOGGER.warn("微信同步vip数据：入参Openid或Vip为空！");
                }
            } else {
                LOGGER.warn("微信同步vip数据：入参为空！");
            }
        } else {
            LOGGER.warn("微信同步vip数据：入参为空！");
        }
        return vip;
    }
}
